package com.example.servlet.goods;

import com.example.bean.Goods;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-03 09:37
 **/
@WebServlet("/goods_car")
public class CarServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            HttpSession session = req.getSession();
            Map<String, Goods> map = (Map<String, Goods>) session.getAttribute("goods");
            if (map == null) {
                map = new HashMap<>();
                session.setAttribute("goods", map);
            }
            resp.setContentType("text/html;charset=utf-8");
            ServletOutputStream os = resp.getOutputStream();
            for (Map.Entry<String, Goods> entry : map.entrySet()) {
                Goods value = entry.getValue();
                String pname = value.getPname();
                double price = value.getPrice();
                int num = value.getNum();
                os.write(("商品名称:" + pname).getBytes("utf-8"));
                os.write("<br>".getBytes("utf-8"));
                os.write(("商品价格:" + price).getBytes("utf-8"));
                os.write("<br>".getBytes("utf-8"));
                os.write(("商品数量:" + num).getBytes("utf-8"));
                os.write("<br>".getBytes("utf-8"));
            }
            os.write("<br>".getBytes("utf-8"));
            os.write("<a href=\"/demo01.html\">请继续浏览商品</a>".getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
